/**
 * @file platform_client.c
 * @brief IoT平台对接客户端实现
 * @details 严格按照MQTT平台与云端交互协议文档实现
 * 
 * @author zyb
 * @date 2025-11-04
 * @version 1.0
 */

#include "../include/platform_client.h"
#include "../../../common/json/include/json_utils.h"
#include "../../../common/logs/include/logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <uuid/uuid.h>

/* ==================== 辅助函数 ==================== */

/**
 * @brief 安全的字符串复制函数（避免strncpy截断警告）
 */
static inline void safe_strncpy(char *dest, const char *src, size_t dest_size) {
    if (dest == NULL || src == NULL || dest_size == 0) {
        return;
    }
    size_t src_len = strlen(src);
    size_t copy_len = (src_len < dest_size - 1) ? src_len : (dest_size - 1);
    memcpy(dest, src, copy_len);
    dest[copy_len] = '\0';
}

#define LOG_MODULE_NAME "PLATFORM_CLIENT"

/* ==================== 私有数据结构 ==================== */

/**
 * @brief 回调函数上下文
 */
typedef struct {
    platform_register_reply_callback_t register_callback;
    platform_signup_reply_callback_t signup_callback;
    platform_model_reply_callback_t model_callback;
    platform_event_reply_callback_t event_callback;
    void* user_data;
    char id[64];
} callback_context_t;

/**
 * @brief 平台客户端私有数据
 */
typedef struct {
    mqtt_client_handle_t mqtt_client;
    platform_device_info_t device;
    
    /* 回调函数 */
    platform_property_set_callback_t property_set_callback;
    platform_service_call_callback_t service_call_callback;
    platform_update_callback_t update_callback;
    void* property_set_user_data;
    void* service_call_user_data;
    void* update_user_data;
    
    /* 回调上下文列表（用于匹配回复） */
    callback_context_t* callbacks;
    size_t callback_count;
    size_t callback_capacity;
    pthread_mutex_t callback_mutex;
    
    /* 主题缓存 */
    char topic_deviceinfo_post[512];
    char topic_deviceinfo_reply[512];
    char topic_property_post[512];
    char topic_property_set[512];
    char topic_event_post[512];
    char topic_event_reply[512];
    char topic_service_call[512];
    char topic_service_report[512];
    char topic_device_update[512];
    char topic_app_post[512];
    char topic_app_set[512];
    
    pthread_mutex_t mutex;
} platform_client_t;

/* ==================== 内部函数声明 ==================== */

static void on_mqtt_message(const char* topic, const uint8_t* payload, size_t payload_len, void* user_data);
static void build_topics(platform_client_t* client);
static int parse_deviceinfo_reply(platform_client_t* client, const char* json_str);
static int parse_property_set(platform_client_t* client, const char* json_str);
static int parse_service_call(platform_client_t* client, const char* json_str);
static int parse_device_update(platform_client_t* client, const char* json_str);
static callback_context_t* find_callback_context(platform_client_t* client, const char* id);
static void remove_callback_context(platform_client_t* client, const char* id);

/* ==================== 函数实现 ==================== */

/**
 * @brief 创建平台客户端
 */
platform_client_handle_t platform_client_create(const platform_client_config_t* config) {
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "开始创建平台客户端");
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    
    if (config == NULL || config->mqtt_client == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置参数为空");
        LOG_ERROR(LOG_MODULE_NAME, "  config: %s", config ? "非空" : "NULL");
        LOG_ERROR(LOG_MODULE_NAME, "  mqtt_client: %s", (config && config->mqtt_client) ? "非空" : "NULL");
        return NULL;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "检查MQTT连接状态...");
    LOG_DEBUG(LOG_MODULE_NAME, "  调用mqtt_client_is_connected...");
    bool is_connected = mqtt_client_is_connected(config->mqtt_client);
    LOG_DEBUG(LOG_MODULE_NAME, "  mqtt_client_is_connected返回: %s", is_connected ? "true" : "false");
    
    if (!is_connected) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT客户端未连接");
        return NULL;
    }
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT客户端已连接");
    
    LOG_DEBUG(LOG_MODULE_NAME, "创建平台客户端结构体...");
    
    platform_client_t* client = (platform_client_t*)malloc(sizeof(platform_client_t));
    if (client == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "内存分配失败");
        return NULL;
    }
    LOG_DEBUG(LOG_MODULE_NAME, "平台客户端结构体内存分配成功");
    
    memset(client, 0, sizeof(platform_client_t));
    client->mqtt_client = config->mqtt_client;
    memcpy(&client->device, &config->device, sizeof(platform_device_info_t));
    LOG_DEBUG(LOG_MODULE_NAME, "设备信息复制完成");
    LOG_DEBUG(LOG_MODULE_NAME, "  产品Key: %s", client->device.product_key);
    LOG_DEBUG(LOG_MODULE_NAME, "  设备名称: %s", client->device.device_name);
    
    /* 初始化互斥锁 */
    LOG_DEBUG(LOG_MODULE_NAME, "初始化互斥锁...");
    if (pthread_mutex_init(&client->mutex, NULL) != 0) {
        LOG_ERROR(LOG_MODULE_NAME, "互斥锁初始化失败");
        free(client);
        return NULL;
    }
    LOG_DEBUG(LOG_MODULE_NAME, "主互斥锁初始化成功");
    
    if (pthread_mutex_init(&client->callback_mutex, NULL) != 0) {
        LOG_ERROR(LOG_MODULE_NAME, "回调互斥锁初始化失败");
        pthread_mutex_destroy(&client->mutex);
        free(client);
        return NULL;
    }
    LOG_DEBUG(LOG_MODULE_NAME, "回调互斥锁初始化成功");
    
    /* 初始化回调列表 */
    LOG_DEBUG(LOG_MODULE_NAME, "初始化回调列表...");
    client->callback_capacity = 16;
    client->callbacks = (callback_context_t*)malloc(sizeof(callback_context_t) * client->callback_capacity);
    if (client->callbacks == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "回调列表内存分配失败");
        pthread_mutex_destroy(&client->callback_mutex);
        pthread_mutex_destroy(&client->mutex);
        free(client);
        return NULL;
    }
    client->callback_count = 0;
    LOG_DEBUG(LOG_MODULE_NAME, "回调列表初始化成功");
    
    /* 构建主题 */
    LOG_DEBUG(LOG_MODULE_NAME, "构建MQTT主题...");
    build_topics(client);
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT主题构建完成");
    
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "构建的MQTT主题:");
    LOG_DEBUG(LOG_MODULE_NAME, "  设备信息上报: %s", client->topic_deviceinfo_post);
    LOG_DEBUG(LOG_MODULE_NAME, "  设备信息回复: %s", client->topic_deviceinfo_reply);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    
    /* 设置MQTT消息回调 */
    LOG_DEBUG(LOG_MODULE_NAME, "设置MQTT消息回调...");
    mqtt_client_set_message_callback(config->mqtt_client, on_mqtt_message, client);
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT消息回调设置完成");
    
    /* 订阅回复主题 */
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "订阅MQTT回复主题...");
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_deviceinfo_reply);
    mqtt_client_subscribe(config->mqtt_client, client->topic_deviceinfo_reply, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_deviceinfo_reply);
    
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_property_set);
    mqtt_client_subscribe(config->mqtt_client, client->topic_property_set, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_property_set);
    
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_event_reply);
    mqtt_client_subscribe(config->mqtt_client, client->topic_event_reply, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_event_reply);
    
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_service_call);
    mqtt_client_subscribe(config->mqtt_client, client->topic_service_call, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_service_call);
    
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_device_update);
    mqtt_client_subscribe(config->mqtt_client, client->topic_device_update, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_device_update);
    
    LOG_DEBUG(LOG_MODULE_NAME, "  主题 %s", client->topic_app_set);
    mqtt_client_subscribe(config->mqtt_client, client->topic_app_set, MQTT_QOS_1);
    LOG_DEBUG(LOG_MODULE_NAME, "  已订阅: %s", client->topic_app_set);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    
    LOG_INFO(LOG_MODULE_NAME, "平台客户端创建成功");
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    
    return (platform_client_handle_t)client;
}

/**
 * @brief 销毁平台客户端
 */
platform_result_t platform_client_destroy(platform_client_handle_t handle) {
    if (handle == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    LOG_DEBUG(LOG_MODULE_NAME, "销毁平台客户端");
    
    /* 取消订阅 */
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_deviceinfo_reply);
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_property_set);
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_event_reply);
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_service_call);
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_device_update);
    mqtt_client_unsubscribe(client->mqtt_client, client->topic_app_set);
    
    /* 释放回调列表 */
    if (client->callbacks) {
        free(client->callbacks);
    }
    
    /* 销毁互斥锁 */
    pthread_mutex_destroy(&client->callback_mutex);
    pthread_mutex_destroy(&client->mutex);
    
    /* 释放内存 */
    free(client);
    
    LOG_DEBUG(LOG_MODULE_NAME, "平台客户端已销毁");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 构建MQTT主题
 */
static void build_topics(platform_client_t* client) {
    snprintf(client->topic_deviceinfo_post, sizeof(client->topic_deviceinfo_post),
             "/sys/%s/%s/thing/deviceinfo/post",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_deviceinfo_reply, sizeof(client->topic_deviceinfo_reply),
             "/sys/%s/%s/thing/deviceinfo/reply",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_property_post, sizeof(client->topic_property_post),
             "/sys/%s/%s/thing/property/post",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_property_set, sizeof(client->topic_property_set),
             "/sys/%s/%s/thing/property/set",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_event_post, sizeof(client->topic_event_post),
             "/sys/%s/%s/thing/event/post",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_event_reply, sizeof(client->topic_event_reply),
             "/sys/%s/%s/thing/event/reply",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_service_call, sizeof(client->topic_service_call),
             "/sys/%s/%s/thing/service/call",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_service_report, sizeof(client->topic_service_report),
             "/sys/%s/%s/thing/service/report",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_device_update, sizeof(client->topic_device_update),
             "/sys/%s/%s/thing/device/update",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_app_post, sizeof(client->topic_app_post),
             "/sys/%s/%s/thing/app/post",
             client->device.product_key, client->device.device_name);
    
    snprintf(client->topic_app_set, sizeof(client->topic_app_set),
             "/sys/%s/%s/thing/app/set",
             client->device.product_key, client->device.device_name);
}

/**
 * @brief 设备上线（register）
 */
platform_result_t platform_device_register(platform_client_handle_t handle,
                                          const platform_device_register_req_t* req,
                                          platform_register_reply_callback_t callback,
                                          void* user_data) {
    if (handle == NULL || req == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "准备发送设备上线请求");
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "请求参数:");
    LOG_DEBUG(LOG_MODULE_NAME, "  类型: %s", req->type);
    LOG_DEBUG(LOG_MODULE_NAME, "  产品Key: %s", req->device.product_key);
    LOG_DEBUG(LOG_MODULE_NAME, "  设备名称: %s", req->device.device_name);
    LOG_DEBUG(LOG_MODULE_NAME, "  设备Secret: %s", 
             strlen(req->device.device_secret) > 0 ? "***已配置***" : "***未配置***");
    LOG_DEBUG(LOG_MODULE_NAME, "  消息ID: %s", req->id);
    
    /* 创建JSON请求 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "创建JSON对象失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    json_utils_add_string_to_object(json_obj, "id", req->id);
    json_utils_add_string_to_object(json_obj, "type", req->type);
    json_utils_add_string_to_object(json_obj, "productKey", req->device.product_key);
    json_utils_add_string_to_object(json_obj, "deviceName", req->device.device_name);
    json_utils_add_string_to_object(json_obj, "deviceSecret", req->device.device_secret);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "生成JSON字符串失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "JSON消息内容:");
    LOG_DEBUG(LOG_MODULE_NAME, "  %s", json_str);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "发送主题: %s", client->topic_deviceinfo_post);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    
    /* 保存回调上下文 */
    pthread_mutex_lock(&client->callback_mutex);
    if (client->callback_count >= client->callback_capacity) {
        /* 扩展容量 */
        size_t new_capacity = client->callback_capacity * 2;
        callback_context_t* new_callbacks = (callback_context_t*)realloc(
            client->callbacks, sizeof(callback_context_t) * new_capacity);
        if (new_callbacks == NULL) {
            pthread_mutex_unlock(&client->callback_mutex);
            free(json_str);
            return PLATFORM_ERROR_MEMORY;
        }
        client->callbacks = new_callbacks;
        client->callback_capacity = new_capacity;
    }
    
    callback_context_t* ctx = &client->callbacks[client->callback_count++];
    memset(ctx, 0, sizeof(callback_context_t));
    safe_strncpy(ctx->id, req->id, sizeof(ctx->id));
    ctx->register_callback = callback;
    ctx->user_data = user_data;
    pthread_mutex_unlock(&client->callback_mutex);
    
    /* 发布消息 */
    LOG_DEBUG(LOG_MODULE_NAME, "正在发送MQTT消息...");
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_deviceinfo_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT消息发送失败，错误码: %d", result);
        remove_callback_context(client, req->id);
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT消息发送成功");
    LOG_INFO(LOG_MODULE_NAME, "等待平台回复，回复主题: %s", client->topic_deviceinfo_reply);
    LOG_INFO(LOG_MODULE_NAME, "========================================");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 设备下线（unregister）
 */
platform_result_t platform_device_unregister(platform_client_handle_t handle,
                                             const platform_device_register_req_t* req,
                                             platform_register_reply_callback_t callback,
                                             void* user_data) {
    /* 与register使用相同的协议格式 */
    return platform_device_register(handle, req, callback, user_data);
}

/**
 * @brief 设备主动注册（signup）
 */
platform_result_t platform_device_signup(platform_client_handle_t handle,
                                         const platform_device_signup_req_t* req,
                                         platform_signup_reply_callback_t callback,
                                         void* user_data) {
    if (handle == NULL || req == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "========================================");
    LOG_INFO(LOG_MODULE_NAME, "准备发送设备主动注册请求");
    LOG_INFO(LOG_MODULE_NAME, "========================================");
    LOG_INFO(LOG_MODULE_NAME, "请求参数:");
    LOG_INFO(LOG_MODULE_NAME, "  类型: %s", req->type);
    LOG_INFO(LOG_MODULE_NAME, "  产品Key: %s", req->product_key);
    LOG_INFO(LOG_MODULE_NAME, "  产品Secret: %s", 
             strlen(req->product_secret) > 0 ? "***已配置***" : "***未配置***");
    LOG_INFO(LOG_MODULE_NAME, "  设备名称: %s", req->device_name);
    LOG_INFO(LOG_MODULE_NAME, "  消息ID: %s", req->id);
    
    /* 创建JSON请求 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "创建JSON对象失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    // 严格按照文档顺序：id, type, productKey, productSecret, deviceName
    json_utils_add_string_to_object(json_obj, "id", req->id);
    json_utils_add_string_to_object(json_obj, "type", req->type);
    json_utils_add_string_to_object(json_obj, "productKey", req->product_key);
    json_utils_add_string_to_object(json_obj, "productSecret", req->product_secret);
    json_utils_add_string_to_object(json_obj, "deviceName", req->device_name);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "生成JSON字符串失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "----------------------------------------");
    LOG_INFO(LOG_MODULE_NAME, "JSON消息内容:");
    LOG_INFO(LOG_MODULE_NAME, "  %s", json_str);
    LOG_INFO(LOG_MODULE_NAME, "----------------------------------------");
    LOG_INFO(LOG_MODULE_NAME, "发送主题: %s", client->topic_deviceinfo_post);
    LOG_INFO(LOG_MODULE_NAME, "----------------------------------------");
    
    /* 保存回调上下文 */
    pthread_mutex_lock(&client->callback_mutex);
    if (client->callback_count >= client->callback_capacity) {
        size_t new_capacity = client->callback_capacity * 2;
        callback_context_t* new_callbacks = (callback_context_t*)realloc(
            client->callbacks, sizeof(callback_context_t) * new_capacity);
        if (new_callbacks == NULL) {
            pthread_mutex_unlock(&client->callback_mutex);
            free(json_str);
            return PLATFORM_ERROR_MEMORY;
        }
        client->callbacks = new_callbacks;
        client->callback_capacity = new_capacity;
    }
    
    callback_context_t* ctx = &client->callbacks[client->callback_count++];
    memset(ctx, 0, sizeof(callback_context_t));
    safe_strncpy(ctx->id, req->id, sizeof(ctx->id));
    ctx->signup_callback = callback;
    ctx->user_data = user_data;
    pthread_mutex_unlock(&client->callback_mutex);
    
    /* 发布消息 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_deviceinfo_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        remove_callback_context(client, req->id);
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "设备主动注册请求已发送");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 获取物模型
 */
platform_result_t platform_get_model(platform_client_handle_t handle,
                                     const platform_model_req_t* req,
                                     platform_model_reply_callback_t callback,
                                     void* user_data) {
    if (handle == NULL || req == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "准备发送获取物模型请求");
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "请求参数:");
    LOG_DEBUG(LOG_MODULE_NAME, "  类型: %s", req->type);
    LOG_DEBUG(LOG_MODULE_NAME, "  产品Key: %s", req->product_key);
    LOG_DEBUG(LOG_MODULE_NAME, "  消息ID: %s", req->id);
    
    /* 创建JSON请求 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "创建JSON对象失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    // 严格按照文档顺序：id, type, productKey
    json_utils_add_string_to_object(json_obj, "id", req->id);
    json_utils_add_string_to_object(json_obj, "type", req->type);
    json_utils_add_string_to_object(json_obj, "productKey", req->product_key);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "生成JSON字符串失败");
        return PLATFORM_ERROR_MEMORY;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "JSON消息内容:");
    LOG_DEBUG(LOG_MODULE_NAME, "  %s", json_str);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    LOG_DEBUG(LOG_MODULE_NAME, "发送主题: %s", client->topic_deviceinfo_post);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    
    /* 保存回调上下文 */
    pthread_mutex_lock(&client->callback_mutex);
    if (client->callback_count >= client->callback_capacity) {
        size_t new_capacity = client->callback_capacity * 2;
        callback_context_t* new_callbacks = (callback_context_t*)realloc(
            client->callbacks, sizeof(callback_context_t) * new_capacity);
        if (new_callbacks == NULL) {
            pthread_mutex_unlock(&client->callback_mutex);
            free(json_str);
            return PLATFORM_ERROR_MEMORY;
        }
        client->callbacks = new_callbacks;
        client->callback_capacity = new_capacity;
    }
    
    callback_context_t* ctx = &client->callbacks[client->callback_count++];
    memset(ctx, 0, sizeof(callback_context_t));
    safe_strncpy(ctx->id, req->id, sizeof(ctx->id));
    ctx->model_callback = callback;
    ctx->user_data = user_data;
    pthread_mutex_unlock(&client->callback_mutex);
    
    /* 发布消息 */
    LOG_DEBUG(LOG_MODULE_NAME, "正在发送MQTT消息...");
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_deviceinfo_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT消息发送失败，错误码: %d", result);
        remove_callback_context(client, req->id);
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT消息发送成功");
    LOG_DEBUG(LOG_MODULE_NAME, "等待平台回复，回复主题: %s", client->topic_deviceinfo_reply);
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 上报属性数据
 * 
 * TODO: 需要实现平台回复处理
 * 1. 检查平台协议文档，确认属性上报是否有回复topic（如 /thing/property/reply）
 * 2. 如果有回复topic，需要：
 *    - 在build_topics中构建回复topic
 *    - 在客户端创建时订阅回复topic
 *    - 在on_mqtt_message中解析回复消息
 *    - 添加属性上报回调函数类型和回调机制
 *    - 在发布消息时生成消息ID，保存回调上下文
 *    - 收到回复时匹配消息ID并调用回调
 * 3. 如果没有专门的回复topic，可能需要：
 *    - 通过deviceinfo/reply统一回复
 *    - 或者通过MQTT QoS机制确认
 */
platform_result_t platform_property_post(platform_client_handle_t handle,
                                         int64_t report_time,
                                         const char* properties_json) {
    if (handle == NULL || properties_json == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    /* 解析properties_json并添加reportTime */
    void* json_obj = json_utils_parse(properties_json);
    if (json_obj == NULL) {
        /* 如果解析失败，尝试创建新对象 */
        json_obj = json_utils_create_object();
        if (json_obj == NULL) {
            return PLATFORM_ERROR_MEMORY;
        }
        /* 将properties_json作为字符串字段 */
        json_utils_add_string_to_object(json_obj, "data", properties_json);
    }
    
    /* 添加reportTime */
    json_utils_add_number_to_object(json_obj, "reportTime", (double)report_time);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    /* 发布消息 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_property_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "属性数据已上报");
    
    // TODO: 实现回复处理
    // - 生成消息ID（如果需要）
    // - 保存回调上下文（如果提供回调函数）
    // - 等待平台回复并调用回调
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 上报设备应用信息
 * 
 * TODO: 需要实现平台回复处理
 * 1. 检查平台协议文档，确认应用信息上报是否有回复topic（如 /thing/app/reply）
 * 2. 如果有回复topic，需要：
 *    - 在build_topics中构建回复topic
 *    - 在客户端创建时订阅回复topic
 *    - 在on_mqtt_message中解析回复消息
 *    - 添加应用信息上报回调函数类型和回调机制
 *    - 在发布消息时生成消息ID，保存回调上下文
 *    - 收到回复时匹配消息ID并调用回调
 * 3. 如果没有专门的回复topic，可能需要：
 *    - 通过deviceinfo/reply统一回复
 *    - 或者通过MQTT QoS机制确认
 */
platform_result_t platform_app_post(platform_client_handle_t handle,
                                   int64_t report_time,
                                   const char* app_info_json) {
    if (handle == NULL || app_info_json == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    /* 解析app_info_json并添加reportTime */
    void* json_obj = json_utils_parse(app_info_json);
    if (json_obj == NULL) {
        /* 如果解析失败，尝试创建新对象 */
        json_obj = json_utils_create_object();
        if (json_obj == NULL) {
            return PLATFORM_ERROR_MEMORY;
        }
        /* 将app_info_json作为字符串字段 */
        json_utils_add_string_to_object(json_obj, "data", app_info_json);
    }
    
    /* 添加reportTime */
    json_utils_add_number_to_object(json_obj, "reportTime", (double)report_time);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    /* 发布消息 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_app_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "设备应用信息已上报");
    
    // TODO: 实现回复处理
    // - 生成消息ID（如果需要）
    // - 保存回调上下文（如果提供回调函数）
    // - 等待平台回复并调用回调
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 设置属性设置回调
 */
platform_result_t platform_set_property_set_callback(platform_client_handle_t handle,
                                                      platform_property_set_callback_t callback,
                                                      void* user_data) {
    if (handle == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    pthread_mutex_lock(&client->mutex);
    client->property_set_callback = callback;
    client->property_set_user_data = user_data;
    pthread_mutex_unlock(&client->mutex);
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 上报事件
 */
platform_result_t platform_event_post(platform_client_handle_t handle,
                                      int64_t report_time,
                                      const char* id,
                                      const char* call_type,
                                      const char* identifier,
                                      const char* output_data_json,
                                      platform_event_reply_callback_t callback,
                                      void* user_data) {
    if (handle == NULL || id == NULL || call_type == NULL || identifier == NULL || output_data_json == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "事件上报: id=%s, identifier=%s, callType=%s",
             id, identifier, call_type);
    
    /* 创建JSON请求 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    json_utils_add_number_to_object(json_obj, "reportTime", (double)report_time);
    json_utils_add_string_to_object(json_obj, "id", id);
    json_utils_add_string_to_object(json_obj, "callType", call_type);
    json_utils_add_string_to_object(json_obj, "identifier", identifier);
    
    /* 解析output_data_json并添加 */
    void* output_data = json_utils_parse(output_data_json);
    if (output_data != NULL) {
        json_utils_add_item_to_object(json_obj, "outputData", output_data);
    } else {
        /* 如果解析失败，作为字符串添加 */
        json_utils_add_string_to_object(json_obj, "outputData", output_data_json);
    }
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    /* 如果是同步事件，保存回调 */
    if (strcmp(call_type, "sync") == 0 && callback != NULL) {
        pthread_mutex_lock(&client->callback_mutex);
        if (client->callback_count >= client->callback_capacity) {
            size_t new_capacity = client->callback_capacity * 2;
            callback_context_t* new_callbacks = (callback_context_t*)realloc(
                client->callbacks, sizeof(callback_context_t) * new_capacity);
            if (new_callbacks == NULL) {
                pthread_mutex_unlock(&client->callback_mutex);
                free(json_str);
                return PLATFORM_ERROR_MEMORY;
            }
            client->callbacks = new_callbacks;
            client->callback_capacity = new_capacity;
        }
        
        callback_context_t* ctx = &client->callbacks[client->callback_count++];
        memset(ctx, 0, sizeof(callback_context_t));
        safe_strncpy(ctx->id, id, sizeof(ctx->id));
        ctx->event_callback = callback;
        ctx->user_data = user_data;
        pthread_mutex_unlock(&client->callback_mutex);
    }
    
    /* 发布消息 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_event_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        if (strcmp(call_type, "sync") == 0) {
            remove_callback_context(client, id);
        }
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "事件已上报");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 上报服务调用结果
 * 
 * TODO: 需要实现平台回复处理
 * 1. 检查平台协议文档，确认服务调用结果上报是否有回复确认
 * 2. 服务调用结果上报是回复平台的服务调用请求，可能需要：
 *    - 通过服务调用的原消息ID进行匹配
 *    - 平台可能通过某种方式确认收到服务调用结果
 *    - 或者通过MQTT QoS机制确认
 * 3. 如果需要明确回复确认，需要：
 *    - 添加服务调用结果上报回调函数类型
 *    - 在发布消息时保存回调上下文
 *    - 等待平台回复确认并调用回调
 */
platform_result_t platform_service_report(platform_client_handle_t handle,
                                          const char* id,
                                          const char* identifier,
                                          const char* input_params_json,
                                          const char* output_params_json) {
    if (handle == NULL || id == NULL || identifier == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "服务调用结果上报: id=%s, identifier=%s", id, identifier);
    
    /* 创建JSON响应 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    json_utils_add_string_to_object(json_obj, "id", id);
    json_utils_add_string_to_object(json_obj, "identifier", identifier);
    
    /* 添加输入参数 */
    if (input_params_json != NULL) {
        void* input_params = json_utils_parse(input_params_json);
        if (input_params != NULL) {
            json_utils_add_item_to_object(json_obj, "input_params", input_params);
        } else {
            json_utils_add_string_to_object(json_obj, "input_params", input_params_json);
        }
    }
    
    /* 添加输出参数 */
    if (output_params_json != NULL) {
        void* output_params = json_utils_parse(output_params_json);
        if (output_params != NULL) {
            json_utils_add_item_to_object(json_obj, "output_params", output_params);
        } else {
            json_utils_add_string_to_object(json_obj, "output_params", output_params_json);
        }
    }
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    /* 发布消息 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_service_report,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "服务调用结果已上报");
    
    // TODO: 实现回复处理
    // - 服务调用结果上报使用原服务调用的消息ID
    // - 平台可能需要确认收到服务调用结果
    // - 如果需要明确确认，需要添加回调机制
    // - 或者通过MQTT QoS机制确认
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 回复设备升级
 */
platform_result_t platform_update_reply(platform_client_handle_t handle,
                                        const char* id,
                                        const char* code) {
    if (handle == NULL || id == NULL || code == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    if (!mqtt_client_is_connected(client->mqtt_client)) {
        return PLATFORM_ERROR_MQTT_NOT_CONNECTED;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "设备升级回复: id=%s, code=%s", id, code);
    
    /* 创建JSON响应 */
    void* json_obj = json_utils_create_object();
    if (json_obj == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    json_utils_add_string_to_object(json_obj, "id", id);
    json_utils_add_string_to_object(json_obj, "type", "update");
    json_utils_add_string_to_object(json_obj, "code", code);
    
    char* json_str = json_utils_print_unformatted(json_obj);
    json_utils_delete(json_obj);
    
    if (json_str == NULL) {
        return PLATFORM_ERROR_MEMORY;
    }
    
    /* 发布消息到deviceinfo/post主题 */
    mqtt_result_t result = mqtt_client_publish(client->mqtt_client,
                                                client->topic_deviceinfo_post,
                                                (const uint8_t*)json_str,
                                                strlen(json_str),
                                                MQTT_QOS_1,
                                                false);
    
    free(json_str);
    
    if (result != MQTT_SUCCESS) {
        return PLATFORM_ERROR_UNKNOWN;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "设备升级回复已发送");
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 设置服务调用回调
 */
platform_result_t platform_set_service_call_callback(platform_client_handle_t handle,
                                                      platform_service_call_callback_t callback,
                                                      void* user_data) {
    if (handle == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    pthread_mutex_lock(&client->mutex);
    client->service_call_callback = callback;
    client->service_call_user_data = user_data;
    pthread_mutex_unlock(&client->mutex);
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 设置设备升级回调
 */
platform_result_t platform_set_update_callback(platform_client_handle_t handle,
                                                platform_update_callback_t callback,
                                                void* user_data) {
    if (handle == NULL) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    platform_client_t* client = (platform_client_t*)handle;
    
    pthread_mutex_lock(&client->mutex);
    client->update_callback = callback;
    client->update_user_data = user_data;
    pthread_mutex_unlock(&client->mutex);
    
    return PLATFORM_SUCCESS;
}

/**
 * @brief 生成消息ID
 */
platform_result_t platform_generate_id(char* id_buffer, size_t buffer_size) {
    if (id_buffer == NULL || buffer_size < 37) {
        return PLATFORM_ERROR_INVALID_PARAM;
    }
    
    uuid_t uuid;
    uuid_generate(uuid);
    uuid_unparse_lower(uuid, id_buffer);
    
    return PLATFORM_SUCCESS;
}

/* ==================== 内部函数实现 ==================== */

/**
 * @brief MQTT消息回调
 */
static void on_mqtt_message(const char* topic, const uint8_t* payload, size_t payload_len, void* user_data) {
    if (topic == NULL || payload == NULL || user_data == NULL) {
        return;
    }
    
    platform_client_t* client = (platform_client_t*)user_data;
    
    /* 确保字符串以\0结尾 */
    char* json_str = (char*)malloc(payload_len + 1);
    if (json_str == NULL) {
        return;
    }
    memcpy(json_str, payload, payload_len);
    json_str[payload_len] = '\0';
    
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_INFO(LOG_MODULE_NAME, "收到MQTT消息");
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    LOG_DEBUG(LOG_MODULE_NAME, "主题: %s", topic);
    LOG_DEBUG(LOG_MODULE_NAME, "长度: %zu 字节", payload_len);
    LOG_DEBUG(LOG_MODULE_NAME, "内容: %s", json_str);
    LOG_DEBUG(LOG_MODULE_NAME, "----------------------------------------");
    
    /* 根据主题分发处理 */
    if (strcmp(topic, client->topic_deviceinfo_reply) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到设备信息回复主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到设备信息回复消息");
        parse_deviceinfo_reply(client, json_str);
    } else if (strcmp(topic, client->topic_property_set) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到属性设置主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到属性设置消息");
        parse_property_set(client, json_str);
    } else if (strcmp(topic, client->topic_event_reply) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到事件回复主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到事件回复消息");
        /* 事件回复处理 */
        parse_deviceinfo_reply(client, json_str); /* 复用相同格式 */
    } else if (strcmp(topic, client->topic_service_call) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到服务调用主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到服务调用消息");
        parse_service_call(client, json_str);
    } else if (strcmp(topic, client->topic_device_update) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到设备升级主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到设备升级消息");
        parse_device_update(client, json_str);
    } else if (strcmp(topic, client->topic_app_set) == 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "匹配到设备应用设置主题，开始解析...");
        LOG_INFO(LOG_MODULE_NAME, "收到设备应用设置消息");
        /* 应用设置处理，可以复用属性设置的解析逻辑 */
        parse_property_set(client, json_str);
    } else {
        LOG_WARN(LOG_MODULE_NAME, "未知主题，未处理: %s", topic);
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "========================================");
    free(json_str);
}

/**
 * @brief 解析设备信息回复
 */
static int parse_deviceinfo_reply(platform_client_t* client, const char* json_str) {
    LOG_DEBUG(LOG_MODULE_NAME, "开始解析设备信息回复...");
    
    void* json_obj = json_utils_parse(json_str);
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "JSON解析失败");
        return -1;
    }
    
    const char* id = json_utils_get_string(json_obj, "id");
    if (id == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "回复消息中缺少id字段");
        json_utils_delete(json_obj);
        return -1;
    }
    
    const char* type = json_utils_get_string(json_obj, "type");
    if (type == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "回复消息中缺少type字段");
        json_utils_delete(json_obj);
        return -1;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "解析到的字段:");
    LOG_DEBUG(LOG_MODULE_NAME, "  消息ID: %s", id);
    LOG_DEBUG(LOG_MODULE_NAME, "  类型: %s", type);
    
    /* 查找回调上下文 */
    LOG_DEBUG(LOG_MODULE_NAME, "查找回调上下文，消息ID: %s", id);
    callback_context_t* ctx = find_callback_context(client, id);
    if (ctx == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "找不到回调上下文，消息ID: %s", id);
        LOG_ERROR(LOG_MODULE_NAME, "  提示: 可能是消息ID不匹配，或回调上下文已被清理");
        json_utils_delete(json_obj);
        return -1;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "找到回调上下文，准备调用回调函数");
    
    /* 严格按照文档：先判断回调类型，因为signup回复的type可能是"register" */
    /* 文档示例中signup回复的type是"register"，需要通过回调类型区分 */
    if (ctx->signup_callback != NULL) {
        /* 主动注册（signup）回复 - 文档示例中type是"register" */
        LOG_INFO(LOG_MODULE_NAME, "处理主动注册回复 (type: %s, 回调: signup_callback)", type);
        platform_device_signup_reply_t reply;
        memset(&reply, 0, sizeof(reply));
        safe_strncpy(reply.id, id, sizeof(reply.id));
        // 文档示例中signup回复的type是"register"，但我们保存原始type
        safe_strncpy(reply.type, type, sizeof(reply.type));
        
        const char* code = json_utils_get_string(json_obj, "code");
        if (code) safe_strncpy(reply.code, code, sizeof(reply.code));
        
        const char* product_key = json_utils_get_string(json_obj, "productKey");
        if (product_key) safe_strncpy(reply.product_key, product_key, sizeof(reply.product_key));
        
        const char* device_name = json_utils_get_string(json_obj, "deviceName");
        if (device_name) safe_strncpy(reply.device_name, device_name, sizeof(reply.device_name));
        
        const char* device_secret = json_utils_get_string(json_obj, "deviceSecret");
        if (device_secret) safe_strncpy(reply.device_secret, device_secret, sizeof(reply.device_secret));
        
        const char* msg = json_utils_get_string(json_obj, "msg");
        if (msg) safe_strncpy(reply.msg, msg, sizeof(reply.msg));
        
        LOG_INFO(LOG_MODULE_NAME, "提取的回复信息（严格按照文档格式）:");
        LOG_INFO(LOG_MODULE_NAME, "  消息ID: %s", id);
        LOG_INFO(LOG_MODULE_NAME, "  类型: %s", type);
        LOG_INFO(LOG_MODULE_NAME, "  结果码: %s", code ? code : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  产品Key: %s", product_key ? product_key : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  设备名称: %s", device_name ? device_name : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  设备Secret: %s", device_secret ? "***已返回***" : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  错误消息: %s", msg ? msg : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "调用主动注册回调函数...");
        
        ctx->signup_callback(&reply, ctx->user_data);
        
        LOG_DEBUG(LOG_MODULE_NAME, "回调函数调用完成");
    } else if (ctx->register_callback != NULL && (strcmp(type, "register") == 0 || strcmp(type, "unregister") == 0)) {
        /* 设备上下线（register/unregister）回复 */
        LOG_INFO(LOG_MODULE_NAME, "处理设备上下线回复 (type: %s, 回调: register_callback)", type);
        platform_device_register_reply_t reply;
        memset(&reply, 0, sizeof(reply));
        safe_strncpy(reply.id, id, sizeof(reply.id));
        if (type) safe_strncpy(reply.type, type, sizeof(reply.type));
        
        const char* code = json_utils_get_string(json_obj, "code");
        if (code) safe_strncpy(reply.code, code, sizeof(reply.code));
        
        const char* reason = json_utils_get_string(json_obj, "reason");
        if (reason) safe_strncpy(reply.reason, reason, sizeof(reply.reason));
        
        const char* cloud_time = json_utils_get_string(json_obj, "cloudTime");
        if (cloud_time) safe_strncpy(reply.cloud_time, cloud_time, sizeof(reply.cloud_time));
        
        LOG_INFO(LOG_MODULE_NAME, "提取的回复信息（严格按照文档格式）:");
        LOG_INFO(LOG_MODULE_NAME, "  消息ID: %s", id);
        LOG_INFO(LOG_MODULE_NAME, "  类型: %s", type);
        LOG_INFO(LOG_MODULE_NAME, "  结果码: %s", code ? code : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  原因: %s", reason ? reason : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  云端时间: %s", cloud_time ? cloud_time : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "调用注册回调函数...");
        
        ctx->register_callback(&reply, ctx->user_data);
        
        LOG_DEBUG(LOG_MODULE_NAME, "回调函数调用完成");
    } else if (ctx->model_callback != NULL && (strcmp(type, "total_model") == 0 || strcmp(type, "simple_model") == 0)) {
        /* 物模型回复 */
        LOG_INFO(LOG_MODULE_NAME, "处理物模型回复 (type: %s, 回调: model_callback)", type);
        platform_model_reply_t reply;
        memset(&reply, 0, sizeof(reply));
        safe_strncpy(reply.id, id, sizeof(reply.id));
        safe_strncpy(reply.type, type, sizeof(reply.type));
        
        const char* code = json_utils_get_string(json_obj, "code");
        if (code) safe_strncpy(reply.code, code, sizeof(reply.code));
        
        void* model_obj = json_utils_get_object(json_obj, "model");
        if (model_obj != NULL) {
            char* model_str = json_utils_print_unformatted(model_obj);
            if (model_str != NULL) {
                reply.model = model_str;
                reply.model_len = strlen(model_str);
            }
        }
        
        LOG_INFO(LOG_MODULE_NAME, "提取的回复信息（严格按照文档格式）:");
        LOG_INFO(LOG_MODULE_NAME, "  消息ID: %s", id);
        LOG_INFO(LOG_MODULE_NAME, "  类型: %s", type);
        LOG_INFO(LOG_MODULE_NAME, "  结果码: %s", code ? code : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "  物模型: %s", reply.model ? "***已返回***" : "(无)");
        LOG_INFO(LOG_MODULE_NAME, "调用物模型回调函数...");
        
        ctx->model_callback(&reply, ctx->user_data);
        
        if (reply.model != NULL) {
            free(reply.model);
        }
        
        LOG_DEBUG(LOG_MODULE_NAME, "回调函数调用完成");
    } else if (ctx->event_callback != NULL && strcmp(type, "update") == 0) {
        /* 事件回复（同步事件的回复） */
        LOG_INFO(LOG_MODULE_NAME, "处理事件回复 (type: %s, 回调: event_callback)", type);
        const char* identifier = json_utils_get_string(json_obj, "identifier");
        const char* code = json_utils_get_string(json_obj, "code");
        
        if (identifier && code) {
            LOG_INFO(LOG_MODULE_NAME, "提取的回复信息（严格按照文档格式）:");
            LOG_INFO(LOG_MODULE_NAME, "  消息ID: %s", id);
            LOG_INFO(LOG_MODULE_NAME, "  事件标识符: %s", identifier);
            LOG_INFO(LOG_MODULE_NAME, "  结果码: %s", code);
            LOG_INFO(LOG_MODULE_NAME, "调用事件回调函数...");
            
            ctx->event_callback(id, identifier, code, ctx->user_data);
            
            LOG_DEBUG(LOG_MODULE_NAME, "回调函数调用完成");
        } else {
            LOG_WARN(LOG_MODULE_NAME, " 事件回复缺少必要字段");
        }
    } else {
        LOG_WARN(LOG_MODULE_NAME, " 无法匹配回调类型或type不匹配");
        LOG_WARN(LOG_MODULE_NAME, "  type: %s", type);
        LOG_WARN(LOG_MODULE_NAME, "  signup_callback: %s", ctx->signup_callback ? "存在" : "不存在");
        LOG_WARN(LOG_MODULE_NAME, "  register_callback: %s", ctx->register_callback ? "存在" : "不存在");
        LOG_WARN(LOG_MODULE_NAME, "  model_callback: %s", ctx->model_callback ? "存在" : "不存在");
        LOG_WARN(LOG_MODULE_NAME, "  event_callback: %s", ctx->event_callback ? "存在" : "不存在");
    }
    
    /* 移除回调上下文 */
    remove_callback_context(client, id);
    
    json_utils_delete(json_obj);
    
    return 0;
}

/**
 * @brief 解析属性设置
 */
static int parse_property_set(platform_client_t* client, const char* json_str) {
    void* json_obj = json_utils_parse(json_str);
    if (json_obj == NULL) {
        return -1;
    }
    
    const char* identifier = json_utils_get_string(json_obj, "identifier");
    void* value_obj = json_utils_get_object(json_obj, "value");
    
    if (identifier != NULL && value_obj != NULL && client->property_set_callback != NULL) {
        char* value_str = json_utils_print_unformatted(value_obj);
        if (value_str != NULL) {
            client->property_set_callback(identifier, value_str, strlen(value_str),
                                         client->property_set_user_data);
            free(value_str);
        }
    }
    
    json_utils_delete(json_obj);
    
    return 0;
}

/**
 * @brief 解析服务调用
 */
static int parse_service_call(platform_client_t* client, const char* json_str) {
    void* json_obj = json_utils_parse(json_str);
    if (json_obj == NULL) {
        return -1;
    }
    
    const char* id = json_utils_get_string(json_obj, "id");
    const char* identifier = json_utils_get_string(json_obj, "identifier");
    void* input_params_obj = json_utils_get_object(json_obj, "input_params");
    
    if (id != NULL && identifier != NULL && input_params_obj != NULL && 
        client->service_call_callback != NULL) {
        char* input_params_str = json_utils_print_unformatted(input_params_obj);
        if (input_params_str != NULL) {
            client->service_call_callback(id, identifier, input_params_str, 
                                         strlen(input_params_str),
                                         client->service_call_user_data);
            free(input_params_str);
        }
    }
    
    json_utils_delete(json_obj);
    
    return 0;
}

/**
 * @brief 解析设备升级
 */
static int parse_device_update(platform_client_t* client, const char* json_str) {
    void* json_obj = json_utils_parse(json_str);
    if (json_obj == NULL) {
        return -1;
    }
    
    if (client->update_callback != NULL) {
        platform_update_info_t update_info;
        memset(&update_info, 0, sizeof(update_info));
        
        const char* id = json_utils_get_string(json_obj, "id");
        if (id) safe_strncpy(update_info.id, id, sizeof(update_info.id));
        
        const char* url = json_utils_get_string(json_obj, "url");
        if (url) safe_strncpy(update_info.url, url, sizeof(update_info.url));
        
        const char* token = json_utils_get_string(json_obj, "token");
        if (token) safe_strncpy(update_info.token, token, sizeof(update_info.token));
        
        const char* md5sum = json_utils_get_string(json_obj, "md5sum");
        if (md5sum) safe_strncpy(update_info.md5sum, md5sum, sizeof(update_info.md5sum));
        
        const char* file_name = json_utils_get_string(json_obj, "file_name");
        if (file_name) safe_strncpy(update_info.file_name, file_name, sizeof(update_info.file_name));
        
        client->update_callback(&update_info, client->update_user_data);
    }
    
    json_utils_delete(json_obj);
    
    return 0;
}

/**
 * @brief 查找回调上下文
 */
static callback_context_t* find_callback_context(platform_client_t* client, const char* id) {
    if (client == NULL || id == NULL) {
        return NULL;
    }
    
    pthread_mutex_lock(&client->callback_mutex);
    
    for (size_t i = 0; i < client->callback_count; i++) {
        if (strcmp(client->callbacks[i].id, id) == 0) {
            pthread_mutex_unlock(&client->callback_mutex);
            return &client->callbacks[i];
        }
    }
    
    pthread_mutex_unlock(&client->callback_mutex);
    
    return NULL;
}

/**
 * @brief 移除回调上下文
 */
static void remove_callback_context(platform_client_t* client, const char* id) {
    if (client == NULL || id == NULL) {
        return;
    }
    
    pthread_mutex_lock(&client->callback_mutex);
    
    for (size_t i = 0; i < client->callback_count; i++) {
        if (strcmp(client->callbacks[i].id, id) == 0) {
            /* 移动后续元素 */
            for (size_t j = i; j < client->callback_count - 1; j++) {
                memcpy(&client->callbacks[j], &client->callbacks[j + 1], sizeof(callback_context_t));
            }
            client->callback_count--;
            break;
        }
    }
    
    pthread_mutex_unlock(&client->callback_mutex);
}

/* 使用json_utils库提供的函数，无需自定义实现 */
